import React, { useEffect, useState } from "react";
import { Table, Button, Modal, Form, Input, Select, message } from 'antd';
import ContentTop from '../../../components/ContentTop';
import { getAccountList, delAccount, editAccount } from "../../../api/account";

export default function AccountList() {
  const { Option } = Select;
  const [deleteRecord, setDeleteRecord] = useState(null);
  const [editRecord, setEditRecord] = useState(null);
  const [editForm] = Form.useForm();
  const [userList, setUserList] = useState([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 5 });

  const columns = [
    {
      title: '账号',
      dataIndex: 'account',
    },
    {
      title: '用户组',
      dataIndex: 'role',
    },
    {
      title: '创建时间',
      dataIndex: 'date',
    },
    {
      title: '操作',
      dataIndex: 'active',
      render: (_, record) => (
        <span>
          <Button type="primary" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button
            type="primary"
            onClick={() => {
              setDeleteRecord(record);
            }}
            danger
            style={{ marginLeft: 10 }}
          >
            删除
          </Button>
        </span>
      ),
    },
  ];

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
  };

  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
    fetchAccounts(newPagination.current, newPagination.pageSize);
  };

  const fetchAccounts = async (currentPage, pageSize) => {
    const res = await getAccountList({ currentPage, pageSize });
    setUserList(res.data.data);
    setPagination((prevPagination) => ({
      ...prevPagination,
      total: res.data.total,
      pageSize,
    }));
  };

  useEffect(() => {
    fetchAccounts(pagination.current, pagination.pageSize);
  }, []);

  const data = userList.map((item) => {
    const date = new Date(item.ctime);
    const Y = date.getFullYear();
    const M = (date.getMonth() + 1).toString().padStart(2, '0');
    const D = date.getDate().toString().padStart(2, '0');
    return {
      key: item.id,
      account: item.account,
      role: item.userGroup,
      date: `${Y}-${M}-${D}`,
    };
  });

  const handleDelete = async () => {
    if (deleteRecord) {
      let res = await delAccount({ id: deleteRecord.key });
      if (res.data.code == 0) {
        setDeleteRecord(null);
        fetchAccounts(pagination.current, pagination.pageSize);
        message.success(res.data.msg)
      } else {
        message.error(res.data.msg)
      }

    }
  };

  const handleEdit = (record) => {
    setEditRecord(record);
    editForm.setFieldsValue({
      account: record.account,
      userGroup: record.role,
    });
  };

  const handleEditSubmit = async () => {
    const values = await editForm.validateFields();
    const updateData = {
      id: editRecord.key,
      account: values.account,
      userGroup: values.userGroup,
    };
    let res = await editAccount(updateData);
    if (res.data.code == 0) {
      setEditRecord(null);
      fetchAccounts(pagination.current, pagination.pageSize);
      message.success(res.data.msg);
    } else {
      message.error(res.data.msg);
    }

  };


  return (
    <>
      <div className="app-content">
        <ContentTop>
          <div className="title">
            账号列表
          </div>
        </ContentTop>


        <div className="content-info">
          <Table
            pagination={pagination}
            onChange={handleTableChange}
            rowKey={(record) => record.key}
            columns={columns}
            dataSource={data}
            rowSelection={{
              type: 'checkbox',
              ...rowSelection,
            }}
          />
        </div>

        <Modal
          title="编辑账号"
          visible={!!editRecord}
          onCancel={() => setEditRecord(null)}
          onOk={handleEditSubmit}
        >
          <Form form={editForm} onFinish={handleEditSubmit}>
            <Form.Item label="账号" name="account">
              <Input />
            </Form.Item>
            <Form.Item label="用户组" name="userGroup" >
              <Select
                placeholder="请选择用户组"
                allowClear
                style={{
                  width: 300,
                  height: 40,
                }}
                name="userGroup"
              >
                <Option value="超级管理员">超级管理员</Option>
                <Option value="普通管理员">普通管理员</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="确认删除"
          visible={!!deleteRecord}
          onOk={handleDelete}
          onCancel={() => setDeleteRecord(null)}
        >
          <p>您确定要删除这个用户吗？</p>
        </Modal>
      </div>
    </>
  );
}
